<?php

namespace App\Http\Model;

use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class HopeLuckDraw extends Base
{
    protected $luckDrawAwardLogTable = 'luck_draw_award_log';//抽奖活动奖品日志表
    protected $luckDrawAwardPoolTable = 'luck_draw_award_pool';//抽奖活动奖品池表
    protected $luckDrawLogTable = 'luck_draw_log';//抽奖活动日志表
    protected $luckDrawUserPropTable = 'hope_user_prop';//抽奖活动用户道具表
    protected $luckDrawUserPropLogTable = 'hope_user_prop_log';//抽奖道具日志表

    protected $table = 'hope_pools_config';
    protected $luckBaseTable = 'hope_draw';//心心相印基本配置
    protected $wPoolTable = 'hope_pools_pool';
    protected $wPoolConfigTable = 'hope_pools_pool_config';
    protected $wOrderTable = 'hope_pools_order';
    protected $wDrawTable = 'hope_pools_draw';
    protected $wWhiteTable = 'hope_pools_white';
    protected $wStatisticsTable = 'hope_pools_statistics';
    protected $giftTable = 'gift_library';
    protected $wGiftTable = 'hope_pools_gift';//展示礼物表
    protected $wPoolUserTable = 'hope_pools_pool_user';//个人池用户
    protected $wPoolWhiteTable = 'hope_pools_pool_white';//心心相印奖池白名单
    protected $spPoolTable = 'hope_pools_pool_child_config';//心心相印特殊礼物配置
    protected $wPoolExGiftList = 'hope_pools_ex_gift_list';//心心相印投入礼物展示配置
    protected $exPoolGifts = 'hope_pools_ex_pool_config';//心心相印奖池配置投入

    //心心相印配置缓存
    protected $wishPoolConfigKey = 'WISHPOOL:CONFIG';//string WISHPOOL:CONFIG => {string}
    //心心相印奖池缓存
    protected $wishLuckPoolKey = 'WISHPOOL:POOL';//string WISHPOOL:POOL => {string}
    
    //心心相印奖池配置缓存
    protected $wishLuckPoolConfigKey = 'WISHPOOL:POOLCONFIG:';//string WISHPOOL:POOLCONFIG:{poolId} => {string}
    //心心相印奖池配置数据缓存
    public $wishLuckPoolDataKey = '{WISHPOOL:POOLDATA:%s}'; //奖池 {WISHPOOL:POOLDATA:{poolId}}
    protected $wishWheelPoolExDataKey = '{WISHPOOL:EXPOOLDATA:%s}'; //投入奖池 {WISHPOOL:EXPOOLDATA:{poolId}}

    //心心相印百抽临时池
    protected $wishLuckPoolCaCheDataKey = '{WISHPOOL:POOLDATA:CACHE:%s}'; //奖池 {WISHPOOL:POOLDATA:CACHE:{poolId}}
    //心心相印特殊玩法奖池缓存
    protected $wishLuckSpPoolDataKey = '{WISHPOOL:SPPOOLDATA:%s:%s}';//奖池 {WISHPOOL:POOLDATA:{poolId}}

    //心心相印个人奖池
    public $wishLuckSelfPoolDataKey = '{WISHPOOL:USERPOOLDATA:%s:%s}';//奖池 {WISHPOOL:USERPOOLDATA:{userId}:{$poolId}}

    //用户抽奖数
    protected $userDrawNumKey = 'WISHPOOL:USERDRAW:NUM:';//string WISHPOOL:USERDRAW:NUM:{userId} => {num}
    //心心相印展示礼物缓存
    protected $wishPoolsGiftKey = 'WISHPOOL:GIFTCONFIG';//string WISHPOOL:GIFTCONFIG => {string}
    //心心相印用户每周抽奖次数缓存
    protected $userDrawNumWeekKey = 'WISHPOOL:USERDRAW:WEEKNUM:';//string WISHPOOL:USERDRAW:WEEKNUM:{ymd}:{userid} => {num}
    //心心相印用户每日抽奖数据统计缓存
    protected $userDrawNumDayKey = 'WISHPOOL:USERDRAW:DAYNUM:';//hash WISHPOOL:USERDRAW:DAYNUM:{ymd}:{userid} => {draw_no/prop_diamond_num/reward_diamond_num}
    protected $_redisKeyUserExpNum = 'WISHPOOL:LUCKDRAW:CACHE:USER:EXP:%d:%s';//使用过的告白币
    protected $nextDoubleAward = 'WISHPOOL:LUCKDRAW:NEXT:DOUBLE:USER:';//下次2倍缓存用户
    protected $getDrawCountByThreeDays = 'WISHPOOL:LUCKDRAW:THREEDAY:COUNTS:';//用户每三天的缓存
    protected $exGiftIdsList = 'WISHPOOL:LUCKDRAW:EX:GIFTLIST';//心心相印投入展示礼物


    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    /**
     * 抽奖活动详情
     */
    public function luckDrawInfo($luckId){
        $info = DB::table($this->luckBaseTable)->where('id', $luckId)->first();
        $info = self::objToArray($info);

        return $info;
    }

    /**
    * 心心相印中奖记录列表
    */
    public function awardListV2($page, $limit, $where){
        $query = DB::table($this->wDrawTable);
        $query = $query->where('reward_diamond_num', '>=', 5200);
        if(!empty($where['user_id'])) {
            $query = $query->where('user_id', $where['user_id']);
        }
        if(!empty($where['id'])) {
            $query = $query->where('id', '>', $where['id']);
        }
        if(!empty($where['created_at_st'])) {
            $query = $query->where('created_at', '>=', $where['created_at_st']);
        }
        $query = $query->selectRaw('sum(gift_num) as gift_num, order_id, gift_id, user_id, created_at')
            ->groupBy('order_id', 'gift_id')
            ->orderBy('order_id', 'desc')
            ->offset($page * $limit)->limit($limit);
        $drawList = $query->get();
        $result = self::objToArray($drawList);

        return $result;
    }

    /**
     * 心心相印滚动列表最新倒叙
     */
    public function marquee($limit){
        $result = DB::table($this->wDrawTable)->orderBy('created_at',"DESC")->limit($limit)->get();
        $result = self::objToArray($result);

        return $result;
    }

    /**
     * 心心相印奖池奖品列表
     */
//    public function awardPoolGiftList(){
//        $list = DB::table($this->luckDrawAwardPoolTable)->where('status',1)->get();
//        $list = self::objToArray($list);
//        $result = [];
//        if(!empty($list)) {
//            foreach($list as $key=>$val) {
//                $val['pool'] = json_decode($val['pool'], true);
//                foreach($val['pool'] as $v2) {
//                    $v2['pool_id'] = $val['id'];
//                    $k2 = $val['id'].'-'.$v2['id'];
//
//                    $result[$k2] = $v2;
//                }
//                $list[$key] = $val;
//            }
//        }
//
//        return $result;
//    }

    /**
     * 获取用户告白币数量
     */
    public function getLuckDrawUserProp($userId, $luckId){
        $info = DB::table($this->luckDrawUserPropTable)
            ->where('luck_id', $luckId)
            ->where('user_id', $userId)
            ->where('status', 1)
            ->where('deleted', 0)
            ->first();
        $info = self::objToArray($info);


        return $info;
    }

    /**
     * 扣减用户告白币
     * @return bool
     */
    public function decrLuckDrawUserProp($userId, $luckId, $num, $desc='心心相印消耗'){
        try {
            if(empty($userId) || empty($num)) {
                return false;
            }
            $num = abs($num);

            $res = DB::table($this->luckDrawUserPropTable)
                ->where('luck_id', $luckId)
                ->where('user_id', $userId)
                ->where('status', 1)
                ->where('deleted', 0)
                ->update([
                    'avail' =>DB::raw('`avail`-' . $num),
                    'used' =>DB::raw('`used`+' . $num),
                ]);
            if(empty($res)) {
                return false;
            }

            $log = [
                "luck_id" => $luckId,
                "user_id" => $userId,
                "change" => 0-$num,
                "type" => 2000,
                "desc" => $desc,
            ];
            $logId = DB::table($this->luckDrawUserPropLogTable)->insertGetId($log);
            if(empty($logId)) {
                return false;
            }
        } catch (\Exception $e) {
            return false;
        }

        return true;
    }

    /**
     * 心心相印奖池奖品列表
     */
//    public function poolAwardList($luckId){
//        $query = DB::table($this->luckDrawAwardPoolTable)->where('luck_id', $luckId);
//        if($luckId == 1000) {
//            $query = $query->where('id', 2008);
//        }else{
//            $query = $query->where('status', 1);
//        }
//        $list = $query->first();
//        $list = self::objToArray($list);
//
//        $result = [];
//        if(!empty($list) && !empty($list['pool'])) {
//            $list = json_decode($list['pool'], true);
//            if(!empty($list)) {
//                $result = $list;
//            }
//        }
//
//        return $result;
//    }

    /**
     * 心心相印奖池奖品列表
     */
//    public function getLuckDrawPoolConfig($poolId){
//        $list = DB::table($this->luckDrawAwardPoolTable)->where('id', $poolId)->first();
//        $list = self::objToArray($list);
//
//        if(!empty($list['pool'])) {
//            $list['pool'] = json_decode($list['pool'], true);
//        }
//
//        return $list;
//    }

    /**
     * 获取许愿奖池配置信息
     */
    public function getWishPoolConfig(){
        $key = $this->wishPoolConfigKey;
        $list = Redis::get($key);
        if(empty($list)){
            $list = DB::table($this->table)->first();
            $list = self::objToArray($list);
            if(!empty($list)) {
                Redis::setex($key, 86400, json_encode($list));
            }
        }else{
            $list = json_decode($list, true);
        }

        return $list;
    }


    public function updateGameRule($data)
    {
        $gameRule = $data['gameRule'];
        $res = DB::table($this->table)->where("id", "=", '1')->update(['rule' => $gameRule]);
        if ($res) {
            $key = $this->wishPoolConfigKey;
            $list = DB::table($this->table)->first();
            $list = self::objToArray($list);
            if (!empty($list)) {
                Redis::setex($key, 86400, json_encode($list));
            }
        }
    }

    public function getGameRule()
    {
        $key = $this->wishPoolConfigKey;
        $list = Redis::get($key);
        if(empty($list)){
            $list = DB::table($this->table)->first();
            $list = self::objToArray($list);
            if(!empty($list)) {
                Redis::setex($key,86400, json_encode($list));
            }
        }

        return $list;
    }

    /**
     * 获取个人池配置
     */
    public function getWishLuckPoolUserId($userId){
        $info = DB::table($this->wPoolUserTable)
            ->where('user_id', $userId)
            ->where('is_delete', 0)
            ->first();
        $info = self::objToArray($info);

        return $info;
    }

    /**
     * 获取心心相印奖池信息
     */
    public function getWishLuckPool(){
        $key = $this->wishLuckPoolKey;
        $list = Redis::get($key);
        if(empty($list)){
            $list = DB::table($this->wPoolTable)->get();
            $list = self::objToArray($list);
            if(!empty($list)) {
                Redis::setex($key, 86400, json_encode($list));
            }
        }else{
            $list = json_decode($list, true);
        }

        $list = array_column($list, null, 'id');

        return $list;
    }

    /**
     * 获取心心相印奖池配置
     */
    public function getWishLuckPoolConfig($poolId){
        $key = $this->wishLuckPoolConfigKey.$poolId;
        $list = Redis::get($key);
        if(empty($list)){
            $list = DB::table($this->wPoolConfigTable)->where('pool_id', $poolId)->get();
            $list = self::objToArray($list);
            if(!empty($list)) {
                Redis::setex($key, 86400, json_encode($list));
            }
        }else{
            $list = json_decode($list, true);
        }

        return $list;
    }

    /**
     * 获取心心相印奖池配置,不查缓存，后台编辑使用
     */
    public function getPoolConfig($poolId){
        $list = DB::table($this->wPoolConfigTable)->where('pool_id', $poolId)->get();
        return self::objToArray($list);
    }

    /**
     * 获取心心相印用户每周抽奖次数缓存
     */
    public function getUserWishLuckDrawNumByWeek($userId){
        $startWeek = Carbon::today()->startOfWeek()->toDateString();
        $endWeek = Carbon::today()->endOfWeek()->toDateString();
        $cacheKey = $this->userDrawNumWeekKey.$startWeek.'|'.$endWeek.':'.$userId;
        $num = Redis::get($cacheKey);
        if(empty($num)) {
            $query = DB::table($this->wOrderTable)
                ->where('created_at', '>=', $startWeek.' 00:00:00')
                ->where('created_at', '<=',  $endWeek.' 23:59:59')
                ->where('user_id', $userId);
            $num = $query->sum('num');
        }
        $num = (int) $num;

        Redis::set($cacheKey, $num);
        Redis::expire($cacheKey, 14*86400);

        return $num;
    }

    /**
     * 获取心心相印用户每日抽奖次数缓存
     */
    public function getUserWishWheelDrawNumDay($userId)
    {
        $num = 0;
        $now = time();
        $ymd = date("Y-m-d", $now);
        $cacheKey = $this->userDrawNumDayKey.$ymd.':'.$userId;
        $num = Redis::get($cacheKey);
        if(empty($num)) {
            $query = DB::table($this->wOrderTable)
                ->where('user_id', $userId)
                ->where('created_at','>=',$ymd.' 00:00:00')
                ->where('created_at', '<=',  $ymd.' 23:59:59')
                ;
            $num = $query->sum('num');
            //今日剩余时间
            $todDayEnd = Carbon::today()->endOfDay()->toDateTimeString();
            $diffTime = (new Carbon)->diffInSeconds($todDayEnd);
            Redis::set($cacheKey, $num);
            Redis::expire($cacheKey, $diffTime);
        }
        $num = (int) $num;
        return $num;
    }

    /**
     * 获取心心相印近三天的抽奖次数缓存
     */
    public function getDrawCountByThreeDays($userId){
        $cacheKey = $this->getDrawCountByThreeDays.$userId;
        $num = Redis::get($cacheKey);
        if(empty($num)){
            $now = time();
            $ymd = date("Y-m-d", $now);
            $query = DB::table($this->wOrderTable)
                ->where('user_id', $userId)
                ->where('created_at','>=',$ymd.' 00:00:00')
                ->where('created_at', '<=',  $ymd.' 23:59:59')
                ;
            $num = $query->sum('num');
            //今日剩余时间
            $todDayEnd = Carbon::today()->addDays(3)->endOfDay()->toDateTimeString();
            $diffTime = (new Carbon)->diffInSeconds($todDayEnd);
            Redis::set($cacheKey, $num);
            Redis::expire($cacheKey, $diffTime);
        }
        $num = (int) $num;
        return $num;
    }

    //累加心心相印用户三天的抽奖次数缓存
    public function incrUserDrawThreeDayNum($userId, $num){
        $cacheKey = $this->getDrawCountByThreeDays.$userId;
        if($num <= 0) {
            return false;
        }
        $new = Redis::INCRBY($cacheKey, $num);

        return $new;
    }

    //累加心心相印用户每日抽奖次数缓存
    public function incrUserDrawDayNum($userId, $num)
    {
        if($num <= 0) {
            return false;
        }
        $now = time();
        $ymd = date("Y-m-d", $now);
        $cacheKey = $this->userDrawNumDayKey.$ymd.':'.$userId;
        $new = Redis::INCRBY($cacheKey, $num);

        return $new;
    }
    /**
     * 获取用户白名单
     */
    public function getWishLuckWhite($userId){
        $list = DB::table($this->wWhiteTable)
            ->where('user_id', $userId)
            ->where('status', 0)
            ->where('is_delete', 0)
            ->get();
        $list = self::objToArray($list);

        return $list;
    }

    //新增心心相印订单记录
    public function addWishLuckOrder($data)
    {
        $id = DB::table($this->wOrderTable)->insertGetId($data);

        return $id;
    }

    //心心相印自指定奖池抽取
    public function drawWishLuckUser($poolId, $userId)
    {
        $key = sprintf($this->wishLuckSelfPoolDataKey, $userId, $poolId);
        $poolConfigId = aliasIndex($key);

        return $poolConfigId;
    }

    //宇宙波波球自指定奖池抽取
    public function drawWishLuck($poolId)
    {
        $key = sprintf($this->wishLuckPoolDataKey, $poolId);
        $poolConfigId = aliasIndex($key);

        return $poolConfigId;
    }

    //累加心心相印用户每周抽奖次数缓存
    public function incrUserDrawWeekNum($userId, $num)
    {
        if($num <= 0) {
            return false;
        }
        $startWeek = Carbon::today()->startOfWeek()->toDateString();
        $endWeek = Carbon::today()->endOfWeek()->toDateString();
        $cacheKey = $this->userDrawNumWeekKey.$startWeek.'|'.$endWeek.':'.$userId;
        $new = Redis::INCRBY($cacheKey, $num);

        return $new;
    }

    //新增心心相印抽奖记录
    public function addWishLuckDraw($data)
    {
        $id = DB::table($this->wDrawTable)->insertGetId($data);

        return $id;
    }

    //更新心心相印白名单
    public function updateWishLuckWhite($id, $orderId)
    {
        $res = DB::table($this->wWhiteTable)->where('id', $id)->update(['status'=>1, 'order_id'=>$orderId]);

        return $res;
    }

    //更新心心相印订单记录
    public function updateWishLuckDraw($orderId, $rewardDiamondNum)
    {
        $res = DB::table($this->wOrderTable)->where('id', $orderId)->update(['reward_diamond_num'=>$rewardDiamondNum]);

        return $res;
    }

    //更新心心相印个人池用户记录
    public function updateWishLuckUserPoolLog($id, $propDiamondNum, $rewardDiamondNum, $drawNum)
    {
        $res = DB::table($this->wPoolUserTable)->where('id', $id)->increment('prop_diamond_num', $propDiamondNum);
        $res = DB::table($this->wPoolUserTable)->where('id', $id)->increment('reward_diamond_num', $rewardDiamondNum);
        $res = DB::table($this->wPoolUserTable)->where('id', $id)->increment('draw_num', $drawNum);

        return $res;
    }

    //更新心心相印用户每日抽奖数据统计缓存
    public function updateWishLuckUserDay($userId, $propDiamondNum, $rewardDiamondNum, $drawNum)
    {
        $now = time();
        $ymd = date("Ymd", $now);
        $cacheKey = $this->userDrawNumDayKey.$ymd.':'.$userId;
        Redis::HINCRBY($cacheKey, 'prop_num', $drawNum);
        Redis::HINCRBY($cacheKey, 'prop_diamond_num', $propDiamondNum);
        Redis::HINCRBY($cacheKey, 'reward_diamond_num', $rewardDiamondNum);

        return 1;
    }

    //个人池用户自动处理移入移出
    public function handleWishLuckUserPool($userId, $poolUser)
    {
        $now = time();
        $ymd = date("Ymd", $now);
        do {
            //判断
            if(empty($poolUser)) {
                //自动移入
                //用户近7天转盘总累计 产出-消耗 产出/消耗
                $info = DB::table($this->wOrderTable)
                    ->where('user_id', $userId)
                    ->where('created_at', '>=', date('Y-m-d H:i:s', ($now - 2*86400)))
                    ->selectRaw('sum(prop_diamond_num) as prop_diamond_num, sum(reward_diamond_num) as reward_diamond_num')
                    ->first();
                $info = objToArray($info);
                $info['prop_diamond_num'] = empty($info['prop_diamond_num']) ? 0 : $info['prop_diamond_num'];//消耗
                $info['reward_diamond_num'] = empty($info['reward_diamond_num']) ? 0 : $info['reward_diamond_num'];//产出
                //盈亏
                $info['profit_loss'] = $info['reward_diamond_num'] - $info['prop_diamond_num'];
                //返奖率%
                $info['profit_rate'] = empty($info['prop_diamond_num']) ? 0 : round(($info['reward_diamond_num']*100)/$info['prop_diamond_num'], 2);

                //获取当前默认个人亏损池
                $config = DB::table($this->wPoolTable)->where('status', 1)->where('pool_type', 2)->where('if_default', 1)->first();
                $config = objToArray($config);
                if(!empty($config)) {
                    $in_profit_loss = empty($config['in_profit_loss']) ? 0 : $config['in_profit_loss'];//进入个人池盈亏
                    $in_profit_rate = empty($config['in_profit_rate']) ? 0 : $config['in_profit_rate'];//进入个人池返奖率%
                    $info['in_profit_loss'] = $in_profit_loss;
                    $info['in_profit_rate'] = $in_profit_rate;
                    //判断
                    if(!empty($in_profit_loss) || !empty($in_profit_rate)) {
                        $flag1 = $flag2 = 0;
                        //盈亏
                        if($in_profit_loss!=0 && $info['profit_loss']>=$in_profit_loss) {
                            $flag1 = 1;
                        }
                        //返奖率%
                        if($in_profit_rate!=0 && $info['profit_rate']>=$in_profit_rate) {
                            $flag2 = 1;
                        }

                        $flag = 0;
                        if(!empty($in_profit_loss) && !empty($in_profit_rate) && $flag1==1 && $flag2==1) {
                            $flag = 1;
                        }elseif(!empty($in_profit_loss) && empty($in_profit_rate) && $flag1==1){
                            $flag = 1;
                        }elseif(empty($in_profit_loss) && !empty($in_profit_rate) && $flag2==1){
                            $flag = 1;
                        }
                        $info['flag'] = $flag;
                        $info['flag1'] = $flag1;
                        $info['flag2'] = $flag2;

                        if($flag == 1) {
                            //移除钻石数
                            $outDiamondNum = intval($info['profit_loss']*$config['out_profit_rate']*0.01*-1);
                            $info['outDiamondNum'] = $outDiamondNum;
                            //初始化心心相印个人奖池配置数据缓存指定用户
                            $poolConfigMap = $this->getWishLuckPoolConfig($config['id']);
                            if(empty($poolConfigMap)) {
                                break;
                            }
                            $poolConfigMap = array_column($poolConfigMap, 'gift_num', 'id');
                            $this->makeWishWheelSelfPoolDataByPoolIdUserId($config['id'], $userId, $poolConfigMap);
                            //新增心心相印个人池用户
                            $poolUserId = $this->addWishLuckPoolUser($userId, 0, $config['id'], $outDiamondNum);
                            $info['poolUserId'] = $poolUserId;

                            break;
                        }
                    }
                }

                //获取当前默认个人盈利池
                $config = DB::table($this->wPoolTable)->where('status', 1)->where('pool_type', 3)->where('if_default', 1)->first();
                $config = objToArray($config);
                if(!empty($config)) {
                    $in_profit_loss = empty($config['in_profit_loss']) ? 0 : $config['in_profit_loss'];//进入个人池盈亏
                    $in_profit_rate = empty($config['in_profit_rate']) ? 0 : $config['in_profit_rate'];//进入个人池返奖率%
                    $info['in_profit_loss'] = $in_profit_loss;
                    $info['in_profit_rate'] = $in_profit_rate;
                    //判断
                    if(!empty($in_profit_loss) || !empty($in_profit_rate)) {
                        $flag1 = $flag2 = 0;
                        //盈亏
                        if($in_profit_loss!=0 && $info['profit_loss']<=$in_profit_loss) {
                            $flag1 = 1;
                        }
                        //返奖率%
                        if($in_profit_rate!=0 && $info['profit_rate']<=$in_profit_rate) {
                            $flag2 = 1;
                        }

                        $flag = 0;
                        if(!empty($in_profit_loss) && !empty($in_profit_rate) && $flag1==1 && $flag2==1) {
                            $flag = 1;
                        }elseif(!empty($in_profit_loss) && empty($in_profit_rate) && $flag1==1){
                            $flag = 1;
                        }elseif(empty($in_profit_loss) && !empty($in_profit_rate) && $flag2==1){
                            $flag = 1;
                        }
                        $info['flag'] = $flag;
                        $info['flag1'] = $flag1;
                        $info['flag2'] = $flag2;

                        if($flag == 1) {
                            //移除钻石数
                            $outDiamondNum = intval($info['profit_loss']*$config['out_profit_rate']*0.01*-1);
                            $info['outDiamondNum'] = $outDiamondNum;
                            //初始化宇宙波波球个人奖池配置数据缓存指定用户
                            $poolConfigMap = $this->getWishLuckPoolConfig($config['id']);
                            if(empty($poolConfigMap)) {
                                break;
                            }
                            $poolConfigMap = array_column($poolConfigMap, 'gift_num', 'id');
                            $this->makeWishWheelSelfPoolDataByPoolIdUserId($config['id'], $userId, $poolConfigMap);
                            //新增宇宙波波球个人池用户
                            $poolUserId = $this->addWishLuckPoolUser($userId, 0, $config['id'], $outDiamondNum);
                            $info['poolUserId'] = $poolUserId;

                            break;
                        }
                    }
                }

            }else{
                //自动移出
                //用户个人池记录
                $info = $this->getWishLuckPoolUserById($poolUser['id']);
                if(empty($info)) {
                    break;
                }
                //不移除
                if(empty($info['out_diamond_num'])) {
                    break;
                }
                //移除钻石数
                $out_diamond_num = empty($info['out_diamond_num']) ? 0 : $info['out_diamond_num'];
                //盈亏
                $info['profit_loss'] = $info['reward_diamond_num'] - $info['prop_diamond_num'];
                //获取奖池配置
                $config = DB::table($this->wPoolTable)->where('id', $poolUser['pool_id'])->first();
                $config = objToArray($config);

                //亏损池
                if($config['pool_type'] == 2) {
                    if($info['profit_loss'] <= $out_diamond_num) {
                        $this->wishWheelDelPoolUser($info['id'], $info['user_id'], 0);
                        $info['亏损池'] = '移除';
                    }
                    break;
                }

                //盈利池
                if($config['pool_type'] == 3) {
                    if($info['profit_loss'] >= $out_diamond_num) {
                        $this->wishWheelDelPoolUser($info['id'], $info['user_id'], 0);
                        $info['盈利池'] = '移除';
                    }
                    break;
                }
            }
        } while (false);

    }

    /**
     * 初始化心心相印个人奖池配置数据缓存指定用户
     */
    public function makeWishWheelSelfPoolDataByPoolIdUserId($poolId, $userId, $data){
        $key = sprintf($this->wishLuckSelfPoolDataKey, $userId, $poolId);
        aliasInit($key, $data);
        return true;
    }

    //新增心心相印个人池用户
    public function addWishLuckPoolUser($userId, $adminId, $poolId, $outDiamondNum)
    {
        $data = [];
        $data['user_id'] = $userId;
        $data['add_time'] = date('Y-m-d H:i:s', time());
        $data['admin_id'] = $adminId;
        $data['pool_id'] = (int) $poolId;
        $data['out_diamond_num'] = (int) $outDiamondNum;

        $id = DB::table($this->wPoolUserTable)->insertGetId($data);

        return $id;
    }

    //获取心心相印个人池根据ID
    public function getWishLuckPoolUserById($id)
    {
        $info = DB::table($this->wPoolUserTable)
            ->where('id', $id)
            ->where('is_delete', 0)
            ->first();
        $info = self::objToArray($info);

        return $info;
    }

    //心心相印删除个人池用户
    public function wishLuckDelPoolUser($id, $userId, $adminId)
    {
        $update = [];
        $update['deladmin_id'] = $adminId;
        $update['del_time'] = date('Y-m-d H:i:s', time());
        $update['is_delete'] = 1;

        $res = DB::table($this->wPoolUserTable)->where('id', $id)->update($update);
        if($res) {
            $keys = Redis::Keys('{WISHPOOL:USERPOOLDATA:'.$userId.':*');
            foreach ($keys as $key) {
                Redis::expire($key, 86400*60);
            }
        }

        return $res;
    }

    /**
     * 心心相印订单中奖记录列表
     */
    public function orderAwardList($orderId){
        $info = DB::table($this->wOrderTable)->where('id', $orderId)->first();
        $info = self::objToArray($info);
        if(empty($info)) {
            return [];
        }

        $drawList = DB::table($this->wDrawTable)
            ->where('order_id', $orderId)
            ->selectRaw('sum(gift_num) as gift_num, sum(prop_diamond_num) as prop_diamond_num, sum(reward_diamond_num) as reward_diamond_num, gift_id, is_sp')
            ->groupBy('gift_id')
            ->get();
        $drawList = self::objToArray($drawList);
        if(empty($drawList)) {
            return [];
        }
        $info['drawList'] = $drawList;

        return $info;
    }

    /**
     * 获取使用过的告白币
     */
    public function getUsed($userId, $luckId){
        $week = date('Y-m-d', strtotime('this week'));
        $key = sprintf($this->_redisKeyUserExpNum, $luckId, $week);
        return intval(Redis::HGET($key, $userId)??0);
    }

    /**
     * 获取用户中奖记录
     */
    public function wishLuckAllAwardList($page, $limit, $where){
        $drawList = DB::table($this->wDrawTable)->where('user_id', $where['user_id'])->orderBy('id','DESC')->offset($page * $limit)->limit($limit)->get();
        $result = self::objToArray($drawList);

        return $result;
    }


    //编辑心心相印配置
    public function editWishLuckConfig($params)
    {
        $upData = [];
        if(!empty($params['need_num'])) {
            $upData['need_num'] = $params['need_num'];
        }
        if(isset($params['new_num'])) {
            $upData['new_num'] = $params['new_num'];
        }
        if(!empty($params['draw_num_1'])) {
            $upData['draw_num_1'] = $params['draw_num_1'];
        }
        if(!empty($params['draw_num_2'])) {
            $upData['draw_num_2'] = $params['draw_num_2'];
        }
        if(!empty($params['draw_img_1a'])) {
            $upData['draw_img_1a'] = $params['draw_img_1a'];
        }
        if(!empty($params['draw_img_1b'])) {
            $upData['draw_img_1b'] = $params['draw_img_1b'];
        }
        if(!empty($params['draw_img_2a'])) {
            $upData['draw_img_2a'] = $params['draw_img_2a'];
        }
        if(!empty($params['draw_img_2b'])) {
            $upData['draw_img_2b'] = $params['draw_img_2b'];
        }
        if(isset($params['full_rate'])) {
            $upData['full_rate'] = $params['full_rate'];
        }
        if(isset($params['in_profit_loss'])) {
            $upData['in_profit_loss'] = $params['in_profit_loss'];
        }
        if(isset($params['in_profit_rate'])) {
            $upData['in_profit_rate'] = $params['in_profit_rate'];
        }
        if(isset($params['out_profit_loss'])) {
            $upData['out_profit_loss'] = $params['out_profit_loss'];
        }
        if(isset($params['out_profit_rate'])) {
            $upData['out_profit_rate'] = $params['out_profit_rate'];
        }

        if(empty($upData)) {
            return 0;
        }

        $res = DB::table($this->table)->update($upData);

        $cacheKey = $this->wishPoolConfigKey;
        Redis::del($cacheKey);

        return $res;
    }

    /**
     * 获取心心相印信息根据ID
     */
    public function getWishLuckPoolById($poolId){
        $info = DB::table($this->wPoolTable)->where('id', $poolId)->first();
        $info = self::objToArray($info);

        return $info;
    }

    /**
     * 初始化心心相印个人奖池配置数据缓存
     */
    public function makeWishLuckSelfPoolData($poolId, $data){
        //查询个人池用户列表
        $list = DB::table($this->wPoolUserTable)->where('is_delete',0)->where('pool_id', $poolId)->get();
        $list = self::objToArray($list);
        if(empty($list)){
            return false;
        }
        foreach($list as $v){
            $key = sprintf($this->wishLuckSelfPoolDataKey, $v['user_id'], $poolId);
            aliasInit($key, $data);
        } 
        return true;
    }

    /**
     * 初始化心心相印配置数据缓存
     */
    public function makeWishLuckPoolData($poolId, $data){
        $key = sprintf($this->wishLuckPoolDataKey, $poolId);
        aliasInit($key, $data);
        $key = sprintf($this->wishLuckPoolCaCheDataKey, $poolId);
        Redis::del($key);
    }
    /**
     * 初始化心心相印特殊玩法配置数据缓存
     */
    public function makeWishLuckSpPoolData($poolId, $giftId, $data){
        $key = sprintf($this->wishLuckSpPoolDataKey, $poolId, $giftId);
        aliasInit($key, $data);
    }
    
    //编辑心心相印
    public function editWishLuckPool($id, $params)
    {
        $upData = [];
        if(!empty($params['status'])) {
            $upData['status'] = $params['status'];
        }
        if(!empty($params['pool_name'])) {
            $upData['pool_name'] = $params['pool_name'];
        }
        if(!empty($params['min_num'])) {
            $upData['min_num'] = $params['min_num'];
        }
        if(!empty($params['max_num'])) {
            $upData['max_num'] = $params['max_num'];
        }
        if(!empty($params['if_default'])) {
            $upData['if_default'] = $params['if_default'];
        }
        if(isset($params['in_profit_loss'])) {
            $upData['in_profit_loss'] = $params['in_profit_loss'];
        }
        if(isset($params['in_profit_rate'])) {
            $upData['in_profit_rate'] = $params['in_profit_rate'];
        }
        if(isset($params['out_profit_rate'])) {
            $upData['out_profit_rate'] = $params['out_profit_rate'];
        }

        if(empty($upData)) {
            return 0;
        }

        $res = DB::table($this->wPoolTable)->where('id', $id)->update($upData);

        $cacheKey = $this->wishLuckPoolKey;
        Redis::del($cacheKey);

        return $res;
    }

    //编辑心心相印奖池配置
    public function editWishLuckPoolConfig($poolId, $id, $giftId, $giftNum)
    {
        $upData = [];
        $upData['gift_id'] = $giftId;
        $upData['gift_num'] = $giftNum;

        $res = DB::table($this->wPoolConfigTable)->where('id', $id)->update($upData);

        $cacheKey = $this->wishLuckPoolConfigKey.$poolId;
        Redis::del($cacheKey);

        return $res;
    }

    /**
     * 获取心心相印奖池根据奖池类型
     */
    public function getWishLuckPoolByDefault($poolType){
        $info = DB::table($this->wPoolTable)->where('pool_type', $poolType)->where('if_default', 1)->first();
        $info = self::objToArray($info);

        return $info;
    }

    //新增心心相印奖池
    public function addWishLuckPool($poolName, $minNum, $maxNum, $poolType, $ifDefault)
    {
        $data = [];
        $data['pool_name'] = $poolName;
        $data['min_num'] = $minNum;
        $data['max_num'] = $maxNum;
        $data['pool_type'] = $poolType;
        $data['if_default'] = $ifDefault;
        $data['status'] = 2;

        $id = DB::table($this->wPoolTable)->insertGetId($data);

        $cacheKey = $this->wishLuckPoolKey;
        Redis::del($cacheKey);

        return $id;
    }

    //新增心心相印奖池配置
    public function addWishLuckPoolConfig($poolId, $itemNo)
    {
        $data = [];
        $data['pool_id'] = $poolId;
        $data['item_no'] = $itemNo;

        $id = DB::table($this->wPoolConfigTable)->insertGetId($data);

        return $id;
    }

    /**
     * 心心相印奖池配置剩余数量
     */
    public function getWishLuckPoolData($poolId){
        $result = [];
        $key = sprintf($this->wishLuckPoolDataKey, $poolId);
        $nameKey = $key . ':ALIAS:' . 'KEYNAME';
        $valKey = Redis::GET($nameKey);
        if(!empty($valKey)) {
            if(Redis::EXISTS($valKey)) {
                $list = Redis::LRANGE($valKey, 0, -1);
                if(!empty($list)) {
                    foreach($list as $val) {
                        if(empty($result[$val])) {
                            $result[$val]['id'] = $val;
                            $result[$val]['num'] = 0;
                        }
                        $result[$val]['num'] = $result[$val]['num'] + 1;
                    }
                }
            }
        }
        $result = array_values($result);

        return $result;
    }

    //新增心心相印白名单
    public function addWishLuckWhite($userId, $giftId, $adminId, $poolId=0)
    {
        $data = [];
        $data['user_id'] = $userId;
        $data['gift_id'] = $giftId;
        $data['admin_id'] = $adminId;
        $data['pool_id'] = $poolId;
        $data['status'] = 0;

        $id = DB::table($this->wWhiteTable)->insertGetId($data);

        return $id;
    }

    //删除心心相印白名单
    public function delWishLuckWhite($whiteId)
    {
        $id = DB::table($this->wWhiteTable)->where('id', $whiteId)->where('is_delete', 0)->update(['is_delete'=>1]);

        return $id;
    }

    //取消投放心心相印白名单
    public function cancelWishLuckWhite($whiteId)
    {
        $id = DB::table($this->wWhiteTable)->where('id', $whiteId)->where('status', 0)->update(['status'=>1]);

        return $id;
    }

    //新增心心相印展示礼物
    public function wishLuckAddGift($giftId, $sort)
    {
        $data = [];
        $data['gift_id'] = $giftId;
        $data['sort'] = $sort;
        $data['is_delete'] = 0;

        $id = DB::table($this->wGiftTable)->insertGetId($data);

        $cacheKey = $this->wishPoolsGiftKey;
        Redis::del($cacheKey);

        return $id;
    }

    //心心相印删除展示礼物
    public function wishLuckDelGift($id)
    {
        $id = DB::table($this->wGiftTable)->where('id', $id)->update(['is_delete'=>1]);

        $cacheKey = $this->wishPoolsGiftKey;
        Redis::del($cacheKey);

        return $id;
    }

    /**
     * 获取心心相印展示礼物
     */
    public function getWishLuckGift(){
        $key = $this->wishPoolsGiftKey;
        $list = Redis::get($key);
        if(empty($list)){
            $list = DB::table($this->wGiftTable)->where('is_delete', 0)->orderBy('sort', 'asc')->get();
            $list = self::objToArray($list);
            if(!empty($list)) {
                Redis::setex($key, 86400, json_encode($list));
            }
        }else{
            $list = json_decode($list, true);
        }

        return $list;
    }

    //获取心心相印个人池用户
    public function getWishLuckPoolUser($userId)
    {
        $info = DB::table($this->wPoolUserTable)
            ->where('user_id', $userId)
            ->where('is_delete', 0)
            ->first();
        $info = self::objToArray($info);

        return $info;
    }

    //查看个人奖池剩余数量
    public function getWishLuckSelfPoolData($poolId, $userId){
        $result = [];
        $key = sprintf($this->wishLuckSelfPoolDataKey, $userId, $poolId);
        $nameKey = $key . ':ALIAS:' . 'KEYNAME';
        $valKey = Redis::GET($nameKey);
        if(!empty($valKey)) {
            if(Redis::EXISTS($valKey)) {
                $list = Redis::LRANGE($valKey, 0, -1);
                if(!empty($list)) {
                    foreach($list as $val) {
                        if(empty($result[$val])) {
                            $result[$val]['id'] = $val;
                            $result[$val]['num'] = 0;
                        }
                        $result[$val]['num'] = $result[$val]['num'] + 1;
                    }
                }
            }
        }
        $result = array_values($result);

        return $result;
    }

    //心心相印自指定奖池中抽取指定的余量
    public function drawWishLuckAppoint($poolId, $poolConfigId, $userId=0)
    {
        if(empty($userId)) {
            $key = sprintf($this->wishLuckPoolDataKey, $poolId);
        }else{
            $key = sprintf($this->wishLuckSelfPoolDataKey, $userId, $poolId);
        }
        $nameKey = $key . ':ALIAS:' . 'KEYNAME';
        $valKey = Redis::GET($nameKey);
        //移除指定参数
        $res = Redis::LREM($valKey, 1, $poolConfigId);
        if($res) {
            //加入另一个池子
            $key_0 = $key.':ALIAS:0';
            $key_1 = $key.':ALIAS:1';
            if($valKey === $key_0) {
                Redis::lpush($key_1, $poolConfigId);
            }else{
                Redis::lpush($key_0, $poolConfigId);
            }
        }
        return $res;
    }

    //统计心心相印数据
    public function wishPoolStatistics($dateSt, $dateEt)
    {
        $info = DB::table($this->wOrderTable)
            ->where('created_at', '>=', $dateSt)
            ->where('created_at', '<=', $dateEt)
            ->selectRaw('count(DISTINCT user_id) as user_num, sum(num) as draw_num, sum(prop_num) as prop_num, sum(prop_diamond_num) as prop_diamond_num, sum(reward_diamond_num) as reward_diamond_num')
            ->first();
        $info = self::objToArray($info);

        return $info;
    }

    //新增心心相印每日统计
    public function addWishPoolStatistics($data)
    {
        $id = DB::table($this->wStatisticsTable)->insertGetId($data);

        return $id;
    }

    //获取心心相印爆出记录
    public function getDrawList($orderId){
        $list = DB::table($this->wDrawTable)
                ->select(DB::raw('sum(gift_num) as gift_num, gift_id,is_sp'))
                ->where('order_id',$orderId)
                ->groupBy('gift_id')
                ->get();
        $list = self::objToArray($list);
        return $list;
    }

    //心心相印特殊玩法新增
    public function insertSpPoolConfig($insert){
        $status = DB::table($this->spPoolTable)->insert($insert);
        return $status;
    }

    //心心相印编辑玩法配置
    public function wishLuckPoolConfigChildEdit($update,$spid){
        $status = DB::table($this->spPoolTable)->where('id',$spid)->update($update);
        return $status;
    }

    //心心相印获取配置
    public function getWishLuckSpPoolConfig($poolId, $poolConfigId, $giftId, $type){
        $res = DB::table($this->spPoolTable)
        ->where('pool_config_id', $poolConfigId)
        ->where('p_gift_id', $giftId)
        ->where('is_deleted',0)
        ->where('p_gift_type',$type)
        ->get();
        $res = objToArray($res);
        return $res;
    }

    //心心相印抽取奖励
    public function drawGiftPool($poolId, $giftId){
        $key = sprintf($this->wishLuckSpPoolDataKey, $poolId, $giftId);
        $poolConfigId = aliasIndex($key);

        return $poolConfigId;
    }

    //获取奖池配置信息
    public function getNewPopPoolConfig($giftIds, $poolId){
        $res = DB::table($this->wPoolConfigTable)
                ->whereIn('gift_id', $giftIds)
                ->where('pool_id',$poolId)
                ->get();
        $res = objToArray($res);
        return $res;
    }

    //查看奖池总数量
    public function getAllPoolAwardNums($poolId){
        $key = sprintf($this->wishLuckPoolDataKey, $poolId);
        $nameKey = $key . ':ALIAS:' . 'KEYNAME';
        $valKey = Redis::GET($nameKey);
        //查看目前队列中总数
        $counts = Redis::LLEN($valKey);
        return $counts;
    }

    //放入临时缓存池
    public function pushCacheWishPool($poolConfigId, $poolId){
        $key = sprintf($this->wishLuckPoolCaCheDataKey, $poolId);
        Redis::lpush($key, $poolConfigId);
    }

    //缓存池子中数量放回原池
    public function pushCacheToOldPool($poolId){
        $key = sprintf($this->wishLuckPoolCaCheDataKey, $poolId);
        $newCacheCount = Redis::LLEN($key);
        for($i = 1; $i<= $newCacheCount; $i++){
            $cachePoolId = Redis::RPOP($key);

            $oldkey = sprintf($this->wishLuckPoolDataKey, $poolId);
            $nameKey = $oldkey . ':ALIAS:' . 'KEYNAME';
            $valKey = Redis::GET($nameKey);
            //加入另一个池子
            $key_0 = $oldkey.':ALIAS:0';
            $key_1 = $oldkey.':ALIAS:1';
            if($valKey === $key_0) {
                Redis::lpush($key_0, $cachePoolId);
                Redis::LREM($key_1,1,$cachePoolId);
            }else{
                Redis::lpush($key_1, $cachePoolId);
                Redis::LREM($key_0,1,$cachePoolId);
            }
        }
    }

    //返回原盒子数据
    public function returnBox($poolId, $poolConfigId){
        $oldkey = sprintf($this->wishLuckPoolDataKey, $poolId);
        $nameKey = $oldkey . ':ALIAS:' . 'KEYNAME';
        $valKey = Redis::GET($nameKey);
        //加入另一个池子
        $key_0 = $oldkey.':ALIAS:0';
        $key_1 = $oldkey.':ALIAS:1';
        if($valKey === $key_0) {
            Redis::lpush($key_0, $poolConfigId);
            Redis::LREM($key_1,1,$poolConfigId);
        }else{
            Redis::lpush($key_1, $poolConfigId);
            Redis::LREM($key_0,1,$poolConfigId);
        }
    }

    //查看是否是彩蛋礼物类型的中包含的礼物
    public function checkColorGift($giftId, $poolConfigId, $userId){
        $gifts = $this->getColorIds();
        return in_array($giftId, $gifts) ? 13 : 0;

//        $info = DB::table($this->spPoolTable)
//        ->where('pool_config_id', $poolConfigId)
//        ->where('is_deleted',0)
//        ->where('p_gift_type',13)
//        ->get();
//        $info = objToArray($info);
//        if(!empty($info)){
//            $ids = array_column($info,'child_gift_id');
//            if(in_array($giftId, $ids)){
//                return 13;
//            }
//        }else{
//            return 0;
//        }
    }

    //触发扭动乾坤后记录方便下次抽取2倍奖励
    public function setNextDrawSp($userId){
        Redis::set($this->nextDoubleAward.$userId,1);
    }

    //获取用户是否触发了双倍奖励
    public function getDoubleStatus($userId){
        $status = Redis::get($this->nextDoubleAward.$userId);
        return $status;
    }

    //删除双倍奖励
    public function delDouble($userId){
        $status = Redis::del($this->nextDoubleAward.$userId);
    }

    //查看奖池配置套盒信息id 
    public function getPoolSpPoolInfo($poolId, $giftIds, $gift_type=12){
        $info = DB::table($this->spPoolTable)
        ->where('pool_id',$poolId)
        ->whereIn('p_gift_id',$giftIds)
        ->where('is_deleted',0)
        ->where('p_gift_type',$gift_type)
        ->get();
        $info = objToArray($info);
        if(!empty($info)){
            return $info;
        }
        return [];    
    }

    //查看配置奖池中的神秘珍宝id
    public function getColorIds(){
        $giftList = DB::table($this->giftTable)->where('gift_type',13)->get(['gift_id']);
        $giftList = objToArray($giftList);
        return array_column($giftList, 'gift_id');

//        $openPool = DB::table($this->wPoolTable)->where('status',1)->get(['id']);
//        $openPool = objToArray($openPool);
//
//        if(!empty($openPool)){
//            $openPoolids = array_column($openPool,'id');
//            $getColorIds = DB::table($this->spPoolTable)->whereIn('pool_id',$openPoolids)->where('p_gift_type',13)->get(['child_gift_id']);
//            $getColorIds = objToArray($getColorIds);
//            if(!empty($getColorIds)){
//                $childIds = array_column($getColorIds,'child_gift_id');
//                return $childIds;
//            }
//        }
//        return [];
    }

    //查看投入展示礼物
    public function getExGift(){
        $data = Redis::get($this->exGiftIdsList);
        if(!empty($data)){
            $data = json_decode($data,true);
        }else{
            $res = DB::table($this->wPoolExGiftList)->where('is_open',1)->first();
            $res = objToArray($res);
            
            if(!empty($res)){
                $gifts = explode(',',$res['gift_ids']);
                $giftsInfo = DB::table($this->giftTable)->whereIn('gift_id',$gifts)->get(['gift_id','name','price','image']);
                $giftsInfo = objToArray($giftsInfo);
                $new = [];
                foreach($giftsInfo as $k=>$v){
                    $new[$k]['gift_id'] = $v['gift_id'];
                    $new[$k]['name'] = $v['name'];
                    $new[$k]['image'] = build_image($v['image']);
                    $new[$k]['price'] = $v['price'];
                }
                $data['gift_list'] = $new;
                $data['is_open'] = $res['is_open'];
                Redis::set($this->exGiftIdsList, json_encode($data));
            }else{
                $data = [
                    'gift_list'=>[],
                    'is_open' => 0
                ];
            }
        }
        return $data;
    }

    //查看投入展示礼物列表
    public function getWishPoolsExGiftList(){
        $res = DB::table($this->wPoolExGiftList)->first();
        $res = objToArray($res);
        return $res;
    }

    //新增投入客户端奖池列表
    public function addWishPoolsExGiftList($insert){
        $insert = DB::table($this->wPoolExGiftList)->insert($insert);
        Redis::del($this->exGiftIdsList);
        return $insert;
    }

    //编辑投入展示礼物列表
    public function updateWishPoolsExGiftList($update, $id){
        $res = DB::table($this->wPoolExGiftList)->where('id',$id)->update($update);
        Redis::del($this->exGiftIdsList);
        return $res;
    }

    //新增奖池投入礼物
    public function insertExGiftForPool($insert){
        $res = DB::table($this->exPoolGifts)->insertGetId($insert);

        return $res;
    }

    //生成投入奖池缓存
    public function makeExPoolRedis($poolId, $datas){
        $key = sprintf($this->wishWheelPoolExDataKey, $poolId);
        $tab = [];
        foreach ($datas as $k => $v) {
            for ($i = 0; $i < $v; $i++) {
                $tab[] = $k;
            }
        }
        shuffle($tab);
        foreach ($tab as $v) {
            Redis::lpush($key, $v);
        }
        return true;
    }

    //查看投放记录
    public function getExForPoolList(){
        $res = DB::table($this->exPoolGifts.' as a')
                ->leftJoin($this->wPoolTable. ' as b','a.pool_id','=','b.id')
                ->leftJoin($this->giftTable.' as c','a.gift_id','=','c.gift_id')
                ->orderBy('a.created_at','DESC')
                ->get(['a.id as id','a.pool_id as pool_id','b.pool_name as pool_name','a.gift_id as gift_id','c.name as gift_name','c.price as gift_price','a.nums as nums','a.created_at as created_at']);
        $res = objToArray($res);
        return $res;
    }

    //获取投入池剩余数量
    public function getWishWheelExPoolData($poolId){
        $result = [];
        $key = sprintf($this->wishWheelPoolExDataKey, $poolId);
        if(!empty($key)) {
            if(Redis::EXISTS($key)) {
                $list = Redis::LRANGE($key, 0, -1);
                if(!empty($list)) {
                    foreach($list as $val) {
                        if(empty($result[$val])) {
                            $result[$val]['id'] = $val;
                            $result[$val]['num'] = 0;
                        }
                        $result[$val]['num'] = $result[$val]['num'] + 1;
                    }
                }
            }
        }
        $result = array_values($result);

        return $result;
    }

    //心心相印自指定投入奖池抽取
    public function drawWishExWheel($poolId)
    {
        $key = sprintf($this->wishWheelPoolExDataKey, $poolId);
        // 计算需要获取的随机元素的数量
        $randomElements = Redis::lrange($key, 0, -1);
        $randomIndex = array_rand($randomElements);
        $poolConfigId = $randomElements[$randomIndex];
        Redis::LREM($key,1,$poolConfigId);
        //更新表抽出
        DB::table($this->exPoolGifts)->where('id',$poolConfigId)->increment('use_num',1);
        return $poolConfigId;
    }

    //白名单抽取
    public function drawWishExWheelWhite($poolId, $poolConfigId)
    {
        $key = sprintf($this->wishWheelPoolExDataKey, $poolId);
        Redis::LREM($key,1,$poolConfigId);

        //更新表抽出
        DB::table($this->exPoolGifts)->where('id',$poolConfigId)->increment('use_num',1);
        return $poolConfigId;
    }

    //心心相印投入奖池配置
    public function getExPoolGifts($poolId)
    {
        $res = DB::table($this->exPoolGifts)->where('pool_id', $poolId)->whereColumn('nums','!=','use_num')->get();
        $res = objToArray($res);
        if(!empty($res)){
            foreach($res as &$v ){
                $v['item_no'] = $v['id'];
            }
        }
        
        return $res;
    }

    //查看对应坚持投入剩余数量
    public function leaveCountsExPoolGifts($poolId){
        $key = sprintf($this->wishWheelPoolExDataKey, $poolId);
        $counts = Redis::LLEN($key);
        return $counts;
    }

    //增加用户恋爱卡
    public function addProp(int $luckId, int $userId, int $num){
        $exist = DB::table($this->luckDrawUserPropTable)
            ->where('luck_id', $luckId)
            ->where('user_id', $userId)
            ->where('status', 1)
            ->where('deleted', 0)
            ->exists();

        //如果存在
        if ($exist) {
            $count = DB::table($this->luckDrawUserPropTable)
                ->where('luck_id', $luckId)
                ->where('user_id', $userId)
                ->where('status', 1)
                ->where('deleted', 0)
                ->increment("avail", $num);
            return $count > 0;
        }

        //如果不存在
        $insert = [
            'luck_id' => $luckId,
            'user_id' => $userId,
            'avail' => $num,
            'used' => 0,
            'status' => 1,
            'deleted' => 0
        ];
        $status = DB::table($this->luckDrawUserPropTable)->insert($insert);
        return $status;
    }

    //记录购买恋爱卡日志
    public function addPropLog(int $luckId, int $userId, int $type, int $change){
        if (empty($luckId) || empty($userId) || empty($type)) {
            return false;
        }
        $insert = [
            'luck_id' => $luckId,
            'user_id' => $userId,
            'type' => $type,
            'change' => $change,
            'desc' => '兑换',
        ];
        $status = DB::table($this->luckDrawUserPropLogTable)->insert($insert);
        return $status;
    }

    //获取可用恋爱卡
    public function getAvail(int $luckId, int $userId){
        $userPropModel = DB::table($this->luckDrawUserPropTable)
            ->where('luck_id', $luckId)
            ->where('user_id', $userId)
            ->where('status', 1)
            ->where('deleted', 0)
            ->first();
        return (int)$userPropModel->avail;
    }

}
